# 中间件
from django.utils.deprecation import MiddlewareMixin
from django_redis import get_redis_connection

from application.common.models import MacAddress
from application.common.models import IpUtil


class WebMainMiddleWare(MiddlewareMixin):

    # 接收请求前
    def process_request(self, request):
        print('*'*20)
        print(MacAddress.get_ip())   # ipv4
        print(MacAddress.get_max_address())  # 网关ip
        # 请求获取MAC地址 ip 存入cookie 做历史记录
        ip = IpUtil.get_ip(request)
        redis_conn = get_redis_connection()
        if not redis_conn.get(ip):
            redis_conn.set(ip, '0')
        else:
            redis_conn.set(ip, str(int(redis_conn.get(ip))+1))
        if not redis_conn.get('ip_count'):
            redis_conn.set('ip_count', '1')
        ip_count = int(redis_conn.get('ip_count'))
        redis_conn.set('ip_count', str(ip_count+1))

        pass

    # 响应请求前
    def process_response(self, request, response):

        return response

